package com.freecat.xmqgct.mvp.ui.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;

import com.freecat.xmqgct.R;
import com.freecat.xmqgct.app.MyApp;
import com.freecat.xmqgct.mvp.model.entity.AccountBean;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：win
 * 时间：2019/10/10
 * 注释：
 */
public class AutoAdapter extends BaseAdapter implements Filterable {
    private Context mContext;
    private List<AccountBean> mList;
    private List<AccountBean> data;


    public AutoAdapter(@NonNull Context context, List<AccountBean> list) {
        mContext = context;
        mList = list;
    }

    @Override
    public int getCount() {
        return mList == null ? 0 : mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position).getAccount();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @NonNull
    @Override
    public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View view = inflater.inflate(R.layout.item_auto_layout, null);
        TextView tvAuto = view.findViewById(R.id.tv_account);
        ImageView ivClose = view.findViewById(R.id.iv_delete);
        tvAuto.setText(mList.get(position).getAccount());
        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyApp.getBoxStore().boxFor(AccountBean.class).remove(mList.get(position).getId());
                mList.remove(position);
                notifyDataSetChanged();
            }
        });
        return view;
    }

    @Override
    public Filter getFilter() {

        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults results = new FilterResults();
                List<AccountBean> list = new ArrayList<>();
                if (constraint != null) {
                    list.addAll(mList);
                }
                results.count = list.size();
                results.values = list;
                return results;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                data = (List<AccountBean>) results.values;
                notifyDataSetChanged();
            }
        };
    }
}
